﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShivamEMR.Model.DataInterfaces.UsersDataInterf;
using ShivamEMR.Model;
using ShivamEMR.Model.DataInterfaces;
using System.Web.Script.Serialization;
using ShivamEMR.Web.Models;
using ShivamEMR.Model.Domain.UIDomain;
using ShivamEMR.Model.Domain.UserDomain;
using System.Web.Security;

namespace ShivamEMR.Web.Controllers
{
    public class HomeController : Controller
    {


        [CustomAuthorizeAttribute(RequiredRight = "Home")]
        public ActionResult Index()
        {      
    
            ViewBag.Message = "Welcome!";

            
            var user = Registry.RepositoryFactory.GetUserRepository().All.SingleOrDefault(u => u.Name == User.Identity.Name);
            List<UserRightGroup> MenuGroups = new List<UserRightGroup>();
            if (user != null  && user.HasCustomRights == false)
            {
                if ( user.Role != null && user.Role.Rights != null)
                {
                    var result = user.Role.Rights.Where(r=>r.Group.Group!="Common").GroupBy(r => r.Group);
                    foreach (var g in result)
                    {
                        var mg = new UserRightGroup() { Group = g.Key.Group, Children = g.Key.Children };
                        mg.Rights = g.Key.Rights.Where(r => r.Type.Type == "Menu"
                            && r.UserRoles.Any(ro=>ro.Role==user.Role.Role)).ToList();
                        MenuGroups.Add(mg);
                    }
                }
            }
            else
                if (user.Rights != null)
                {
                    var result = user.Rights.GroupBy(r => r.Group);
                    foreach (var g in result)
                    {
                        var mg = new UserRightGroup() { Group = g.Key.Group, Children = g.Key.Children };
                        mg.Rights = g.Key.Rights.Where(r => r.Type.Type == "Menu").ToList();
                        MenuGroups.Add(mg);
                    }
                }

                //foreach (var mg in user.Role.DashboardMenu.Children)
                //    MenuGroups.Add(mg);
            ViewBag.MenuGroups = MenuGroups;

            MvcApplication.MsgDetail.NeedToShow = true;
            MvcApplication.MsgDetail.MessageHeading = "Dashboard";
            MvcApplication.MsgDetail.MessageDesc = User.Identity.Name + " Welcome to your dashboard";
            

            return View();         
           
        }

      

        [Authorize]
        public ActionResult About()
        {
            return View();
        }
       
    }
}
